package com.dzsw.strings;

/**
 * 测试合并字符串的三种方法耗时
 *
 * @author sunz
 * @version 1.0
 * @CreateTime 2021-04-21-15:11
 */
public class CombineStringMain {
    private static final int forTimes = 10000;

    private static final String url = "http://localhost:8080/testSomeThings?";
    private static final String uId = "100180";
    private static final String userName = "testName";
    private static final String userPwd = "Nux321mXJc";

    public static void main(String[] args) {
        testStringAddFor();
        testStringBuilderFor();
        testStringFormatFor();
    }

    private static void testStringFormatFor() {
        System.out.println("--------------testStringFormatFor---------------");
        Runtime runtime = Runtime.getRuntime();
        long memory = runtime.freeMemory();
        long beginTime = System.currentTimeMillis();
        for (int i = 0; i <= forTimes; i++) {
            String resultStr = String.format("%suId=%s&userName=%s&userPwd=%s", url, uId, userName, userPwd);
        }

        // System.out.println(resultStr);
        System.out.println(System.currentTimeMillis() - beginTime);
        System.out.println((memory - runtime.freeMemory()) / 10000 + "W");
    }


    private static void testStringBuilderFor() {
        System.out.println("--------------testStringBuilderFor---------------");
        Runtime runtime = Runtime.getRuntime();
        long memory = runtime.freeMemory();

        long beginTime = System.currentTimeMillis();
        StringBuilder resultBuilder = new StringBuilder();
        for (int i = 0; i <= forTimes; i++) {
            resultBuilder.append(url).append("uId=").append(uId).append("&userName=").append(userName)
                    .append("&userPwd=").append(userPwd);
        }
        String resultStr = resultBuilder.toString();
        //   System.out.println(resultStr);
        System.out.println(System.currentTimeMillis() - beginTime);
        System.out.println((memory - runtime.freeMemory()) / 10000 + "W");
    }

    private static void testStringAddFor() {
        System.out.println("--------------testStringAddFor---------------");
        Runtime runtime = Runtime.getRuntime();
        long memory = runtime.freeMemory();
        long beginTime = System.currentTimeMillis();
        String resultStr = "";
        for (int i = 0; i <= forTimes; i++) {
            resultStr += url + "uId=" + uId + "&userName=" + userName + "&userPwd=" + userPwd;
        }

//        System.out.println(resultStr);
        System.out.println(System.currentTimeMillis() - beginTime);
        System.out.println((memory - runtime.freeMemory()) / 10000 + "W");
    }

}
